package com.hmall.search.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.hmall.api.domain.dto.ItemDoc;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class ltemChangeListener {

    @Autowired
    private ElasticsearchClient elasticsearchClient;


    //更新ES库(新增或修改)
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.change.queue"),
            exchange = @Exchange(value = "item.change.exchange"),
            key = {"add","update"}
    ))
    public void itemChange(String message) throws IOException {
        if(ObjectUtil.isNotEmpty(message)){
            //1、将message转成JavaBean
            ItemDoc doc = JSONUtil.toBean(message, ItemDoc.class);
            //2、将转成ItemDoc的对象写到ES中
            elasticsearchClient.index(
                    b -> b.index("items")
                            .id(doc.getId().toString())
                            .document(doc));
        }

    }





    //局部更新（更新库存数量）
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.modify.queue"),
            exchange = @Exchange(value = "item.change.exchange"),
            key = {"update"}
    ))
    public void itemModify(String message) throws IOException {
        if(ObjectUtil.isNotEmpty(message)){
            // 1. 将message转成JavaBean
            ItemDoc doc = JSONUtil.toBean(message, ItemDoc.class);
            // 2. 局部更新ES中的文档
            elasticsearchClient.update(b -> b.index("items")
                    .id(doc.getId().toString())
                    .doc(Map.of("stock", doc.getStock())), ItemDoc.class);
        }
    }



    //删除ES库的商品
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.delete.queue"),
            exchange = @Exchange(value = "item.change.exchange"),
            key = {"delete"}
    ))
    public void itemDelete(String message) throws IOException {
        if(ObjectUtil.isNotEmpty(message)){
            // 将message转成JavaBean获取ID
            ItemDoc doc = JSONUtil.toBean(message, ItemDoc.class);
            // 根据ID删除ES中的文档
            elasticsearchClient.delete(b -> b.index("items")
                    .id(doc.getId().toString()));
        }
    }

}